CalendarService    = Packages.com.google.gdata.client.calendar.CalendarService;
gdata              = Packages.com.google.gdata.data;
CalendarEntry      = Packages.com.google.gdata.data.calendar.CalendarEntry;
PlainTextConstruct = Packages.com.google.gdata.data.PlainTextConstruct;
TimeZoneProperty   = Packages.com.google.gdata.data.calendar.TimeZoneProperty;
HiddenProperty     = Packages.com.google.gdata.data.calendar.HiddenProperty;
ColorProperty      = Packages.com.google.gdata.data.calendar.ColorProperty;
Where              = Packages.com.google.gdata.data.extensions.Where;
CalendarService    = Packages.com.google.gdata.client.calendar.CalendarService;
gdata              = Packages.com.google.gdata.data;
AclEntry           = Packages.com.google.gdata.data.acl.AclEntry;
AclScope           = Packages.com.google.gdata.data.acl.AclScope;
CalendarAclRole    = Packages.com.google.gdata.data.calendar.CalendarAclRole;
CalendarFeed       = Packages.com.google.gdata.data.calendar.CalendarFeed;
SelectedProperty   = Packages.com.google.gdata.data.calendar.SelectedProperty;

function main( ui) {
  //getQueryParameters()
  var userObject = ui.getQueryParameters().getFirst("json");
  Log.debug(userObject);
  
  if( null == userObject ) throw new java.lang.Exception("param json is null!");
  var o = new JSONObject( userObject );
  var result = null;
  
  try{
       result = createUser( o );
  } catch( e ) {
      Log.debug("error creating user" + e);
      var vDebug = ""; 
      for (var prop in e) 
      {  
         Log.debug("property=" + prop);
         Log.debug("value=" + e[prop]);
         vDebug += "property: "+ prop+ " value: ["+ e[prop]+ "]\n"; 
      } 
    //vDebug += "toString(): " + " value: [" + e.toString() + "]"; 
    
    Log.debug(vDebug);
     var ex = "{ exception: { message: '" + e + "' } }";
      return ex;
   
  }
}


function createCalendar( partecipantEmail ,timeZone) { 
   Log.debug("creatingCalendar, partecipantEmail=" + partecipantEmail + " timeZone=" + timeZone);
    var service = new CalendarService("demo-calendar-1");
    var username = "soulsoftware2010@gmail.com";
    var password = "2010soulsoftware";
    service.setUserCredentials(username, password);

    try {
             // Create the calendar
             var calendar = new CalendarEntry();
               
             calendar.setTitle(new PlainTextConstruct(""));
             calendar.setSummary(new PlainTextConstruct("This calendar contains the practice schedule and game times."));
             calendar.setTimeZone(new TimeZoneProperty (timeZone));
             calendar.setHidden(HiddenProperty.FALSE);
             calendar.setColor(new ColorProperty("#2952A3"));
             calendar.addLocation(new Where("","",timeZone));
             Log.debug("calendar=" + calendar);            
               // Insert the calendar
             var postUrl = new java.net.URL("https://www.google.com/calendar/feeds/default/owncalendars/full");
             var returnedCalendar = service.insert(postUrl, calendar);
             Log.debug("returnedCalendar=" + returnedCalendar);            
             var idCalendar = returnedCalendar.getId();
      
             //SHARE CALENDAR
             var index=idCalendar.lastIndexOf("/");
             idCalendar=idCalendar.substring(++index);
             Log.debug("calendarId=" + idCalendar);            
             var entry = new AclEntry();
             entry.setScope(new AclScope(AclScope.Type.USER, partecipantEmail));
             entry.setRole(CalendarAclRole.READ);
  
             var aclUrl =
             new java.net.URL("https://www.google.com/calendar/feeds/"+idCalendar+"/acl/full");
  
             var result = service.insert(aclUrl, entry);
      
             // Force Rename and TimeZone
             var feedUrl = new java.net.URL("https://www.google.com/calendar/feeds/default/allcalendars/full");
             var resultFeed = service.getFeed(feedUrl, CalendarFeed);
      
             for (var i = 0; i < resultFeed.getEntries().size(); i++) {
                 var entry = resultFeed.getEntries().get(i);
                 if (entry.getTitle().getPlainText().equals(idCalendar)){
                    var resultFeed = service.getFeed(postUrl, CalendarFeed);
                    calendar = resultFeed.getEntries().get(0);
                    var timeZone = new TimeZoneProperty();
                    timeZone.setValue(timeZone);
                    calendar.setTimeZone(timeZone);
                    calendar.setSelected(SelectedProperty.TRUE);
                    calendar.update();
                    break;
               }
            }
            Log.debug("returning calendar=" + returnedCalendar);
            return returnedCalendar;
    }
    catch( e ) {
      Log.debug("calendar is null" + e);
      throw e;
  //    return null;
    }
      Log.debug("calendar is null");
  throw e;
      //return null;
}

function createUser( userObject ) {
  var returnedCalendar;
  var idCalendar;
  Log.debug("creating user");
  try{
       var USER_ID_JSON_KEY    = "USER_ID"; 
       var PREFERENCE_JSON_KEY = "PREFERENCE";
       var partecipantEmail=userObject.getString(USER_ID_JSON_KEY); 
    
       var o = new JSONObject( userObject.getString(PREFERENCE_JSON_KEY) );
    
       returnedCalendar=createCalendar( userObject.getString(USER_ID_JSON_KEY),o.getString("TIMEZONE") ); 
       if (returnedCalendar!=null ){
         Log.debug("returned calendar=" + returnedCalendar);
           idCalendar = returnedCalendar.getId();
           var index=idCalendar.lastIndexOf("/");
           idCalendar=idCalendar.substring(++index);
         
           var a = new UserEntity();
           a.userId=userObject.getString(USER_ID_JSON_KEY);
           a.name=java.net.URLDecoder.decode(idCalendar);
           a.deviceId="";
           a.preferences = userObject.getString(PREFERENCE_JSON_KEY);
           EntityManager.createUser( a );
           return "{result:'"+idCalendar+"'}";
       } 
  }catch( e ){
        Log.info("Remove Google calendar... ");
        
        if ( returnedCalendar !=null && BOLEntityManager.removeCalendarEntry( returnedCalendar )){
             throw new java.lang.Exception("Google calendar error....manually remove the calendar");
        }
        throw e;
  }
  return "{'exception':{'message':'Google calendar error'}}";
  //throw new java.lang.Exception("Google calendar error");
}
